package net.xujialiang.XTestRPA.Service;

import net.xujialiang.XTestRPA.Entity.Tenant.XRPATenant;
import net.xujialiang.XTestRPA.Entity.XRPAUser;
import net.xujialiang.XTestRPA.Repository.Tenant.TenantRepository;
import net.xujialiang.XTestRPA.Repository.UserRepository;
import net.xujialiang.XTestRPA.Service.Tenant.XRPATenantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;

@Service
public class XRPAUserService {

    @Autowired
    UserRepository userRepository;
    @Autowired
    TenantRepository tenantRepository;

    /**
     * 创建用户
     * @param username 账号
     * @param password 密码
     * @param ttc 租户号
     * @param nickName 昵称
     */
    public void createuser(String username, String password, String ttc, String nickName, Boolean needUpdatePed) throws Exception {
        String encPassword = new BCryptPasswordEncoder().encode(password);
        XRPAUser entity = XRPAUser.builder()
                .username(username)
                .password(encPassword)
                .ttc(ttc)
                .nickName(nickName)
                .needModifyPwd(needUpdatePed)
                .build();
        userRepository.save(entity);
    }

    /**
     * 检查租户下的用户数是否超过限制
     * @param ttc
     * @throws Exception
     */
    public Boolean checkLimit(String ttc) throws Exception {
        // 判断是否超过租户套餐上限
        long count = userRepository.countByTtc(ttc);
        Optional<XRPATenant> ret = tenantRepository.findByTtc(ttc);
        XRPATenant tenant = ret.get();
        long limit = tenant.getEnvLimit();
        if(count >= limit){
            return false;
        }
        return true;
    }

    /**
     * 删除用户
     * @param username 用户名
     * @param ttc 租户号
     * @throws Exception
     */
    public void deluser(String username, String ttc) throws Exception {
        Optional<XRPAUser> user = userRepository.findByTtcAndUsername(ttc, username);
        if(user.isEmpty()){
            throw new Exception("用户不存在");
        }else{
            userRepository.delete(user.get());
        }
    }

    /**
     * 更新用户昵称
     * @param username 用户名
     * @param ttc 租户号
     * @param nickName 昵称
     * @throws Exception
     */
    public void updateNickName(String username, String ttc, String nickName) throws Exception {
        Optional<XRPAUser> user = userRepository.findByTtcAndUsername(ttc, username);
        if(user.isEmpty()){
            throw new Exception("用户不存在");
        }else{
            XRPAUser entity = user.get();
            entity.setNickName(nickName);
            userRepository.save(entity);
        }
    }

    /**
     * 根据用户名查询用户信息
     *
     * @param username 用户名
     * @return 用户信息
     */
    public XRPAUser queryUserByNameAndTTC(String username, String ttc) {
        Optional<XRPAUser> user = userRepository.findByTtcAndUsername(ttc, username);
        if(user.isEmpty()){
            return null;
        }else{
            return user.get();
        }
    }

    /**
     * 查询租户下的所有用户
     * @param ttc 租户号
     * @param page 页码
     * @param pageSize 每页数据条数
     * @return
     * @throws Exception
     */
    public Map<String, Object> fetchUserByTTCAndPage(String ttc, String account, String nickname, int page, int pageSize) throws Exception {
        Sort sort = Sort.by(Sort.Direction.DESC,  "id");
        PageRequest pr =  PageRequest.of(page,pageSize, sort);
        if(account.equals("")){
            account = null;
        }
        if(nickname.equals("")){
            nickname = null;
        }
        Page<XRPAUser> pageData = userRepository.findByTtcAndAccountAndNickName( ttc, account, nickname, pr);
        Map<String, Object> ret = new LinkedHashMap<>();
        ret.put("totalPages", pageData.getTotalPages());
        ret.put("totalCount", pageData.getTotalElements());
        ret.put("page", page);
        ret.put("pageSize", pageSize);
        ret.put("list", pageData.getContent());
        return ret;
    }


    /**
     * 修改密码
     * @param username 用户名
     * @param ttc 租户号
     * @param newpwd 新密码
     * @throws Exception
     */
    public void updatePwd(String username, String ttc, String newpwd, String oldPwd) throws Exception {
        if(newpwd == null){
            throw new Exception("新密码不正确");
        }
        Optional<XRPAUser> user = userRepository.findByTtcAndUsername(ttc, username);
        if(user.isEmpty()){
            throw new Exception("用户不存在");
        }else{
            XRPAUser entity = user.get();
            //验证旧密码
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            boolean isValid = passwordEncoder.matches(oldPwd, entity.getPassword());
            if(isValid){
                String encPassword = new BCryptPasswordEncoder().encode(newpwd);
                entity.setPassword(encPassword);
                userRepository.save(entity);
            }else{
                throw  new Exception("旧密码不正确");
            }
        }
    }

}
